package com.whfc.base.xxl.job;

import com.whfc.XxlJobConfig;
import com.whfc.base.dao.AppFileExportMapper;
import com.whfc.base.entity.AppFileExport;
import com.whfc.common.file.FileHandler;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description 导出记录任务
 * @Author hw
 * @Date 2021-09-02 16:29
 * @Version 1.0
 */
@Component
@ConditionalOnBean(XxlJobConfig.class)
public class FileExportJob {

    @Autowired
    private AppFileExportMapper appFileExportMapper;


    @Autowired
    private FileHandler fileHandler;

    @XxlJob("updateFileFailureState")
    public void updateFailureState() {
        try {
            XxlJobHelper.log("更新导出记录失败状态");
            appFileExportMapper.updateFailureState();
        } catch (Exception e) {
            XxlJobHelper.handleFail("更新导出记录失败状态失败 error:" + e.getMessage());
        }
    }

    @XxlJob("delOverdueFile")
    public void delOverdueFile() {
        try {
            XxlJobHelper.log("删除过期文件");
            List<AppFileExport> appFileExports = appFileExportMapper.selectByOverdue();
            if (appFileExports.isEmpty()) {
                XxlJobHelper.handleSuccess("没有过期文件需要删除");
                return;
            }
            XxlJobHelper.log("开始删除过期文件信息 ：{}", appFileExports);
            List<String> urls = appFileExports.stream().map(AppFileExport::getFileUrl).collect(Collectors.toList());
            List<Integer> ids = appFileExports.stream().map(AppFileExport::getId).collect(Collectors.toList());
            fileHandler.delete(urls);
            appFileExportMapper.updateDelState(ids);
            XxlJobHelper.handleSuccess();
        } catch (Exception e) {
            XxlJobHelper.handleFail("更新导出记录失败状态失败 error:" + e.getMessage());
        }
    }

}
